using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

using MetX;
using MetX.IO;
using MetX.Data;
using Mvp.Xml.XInclude;
using System.IO;

namespace MetX.Gather
{
    public class CommandLine : GatherProvider
    {
        public override int GatherNow(StringBuilder sb, string[] args)
        {
            if (args.Length > 0 && (Token.First(args[0]).ToLower() == "xml"))
            {
                string XmlAction = Token.Get(args[0], 2, " ");
                string XmlSettings = Token.After(args[0], 2, " ");
                XmlDocument xmldoc = new XmlDocument();
                StringBuilder xmlSB = new StringBuilder();

                if (args[2].IndexOf("<?xml") == -1)
                {
                    if (File.Exists(args[1]))
                    {
                        using (XmlTextReader xtr = new XmlTextReader(args[1]))
                        using (XIncludingReader xir = new XIncludingReader(xtr))
                            xmldoc.Load(xir);
                    }
                    else if (File.Exists(args[2]))
                    {
                        using (XmlTextReader xtr = new XmlTextReader(args[2]))
                        using (XIncludingReader xir = new XIncludingReader(xtr))
                            xmldoc.Load(xir);
                    }
                }

                if (xmldoc.DocumentElement == null || !xmldoc.HasChildNodes)
                {
                    using (StringReader sr = new StringReader(args[2]))
                    using (XIncludingReader xir = new XIncludingReader(sr))
                        xmldoc.Load(xir);
                }

                if (xmldoc.DocumentElement != null && xmldoc.HasChildNodes)
                {
                    switch (XmlAction.ToLower())
                    {
                        case "sync-builder":
						case "synch-builder":
							switch (XmlSettings)
							{
								case "1":
								case "append":
									sb.Append(xmldoc.OuterXml);
									break;
							}
							break;
                    }
                }
            }
            else
            {
                switch (args.Length)
                {
                    case 1:
                        sb.Append(FileSystem.GatherOutput(args[0], null, null, -1));
                        return 0;
                    case 2:
                        sb.Append(FileSystem.GatherOutput(args[0], args[1], null, -1));
                        return 0;
                    case 3:
                        sb.Append(FileSystem.GatherOutput(args[0], args[1], args[2], int.Parse(args[3])));
                        return 0;
                }
            }
            return -1;
        }
    }
}
